<?php
class Controller_Register extends Controller_Action
{

	public function __construct(Controller_Front $frontController)
	{
		parent::__construct('register', $frontController);
	}
		
	public function indexAction()
	{
		Log::info('register - index');
		
		$this->view()->display('user_register.tpl');
	}
	
	public function checkAction()
	{
		if (!isset($_POST['login'], $_POST['password'], $_POST['email'])) {
			$this->view()->assign('fail_info', 'go to register panel first');
			return $this->view()->display('fail.tpl');
		}
		
	    if (empty($_POST['login']) ||  empty($_POST['password']) || empty($_POST['email'])) {
			$this->view()->assign('fail_info', 'enter data');
			return $this->view()->display('fail.tpl');
		}
		
		// FIXME: catch exception
		
		$user = new Users();
		$user->setLogin($_POST['login'])
			->setPassword($_POST['password'])
			->setEmail($_POST['email']);
			
		if (Manager_User::isRegistered($user)) {
			$this->view()->assign('fail_info', 'Problem with your register');
			return $this->view()->display('fail.tpl');
		}
		
		try {
			// set permissions as user
			$user->setUserspermissions(
				Manager_User::getPermission(Manager_User::PERMISSION_USER)
				);
			// set default preference group
			$user->setIdPreferencesGroup(
				Manager_PreferenceGroup::getDefault()->getIdPreferencesGroup()
			);
			// set register date
			$user->setRegisterdate(time());
			
			$user->save();
			
			Manager_User::logout();
			
			return $this->ok('You are now register in');
		} catch (Exception $e) {
			return $this->fail($e->getMessage());
		}
	}		
}